/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import com.alibaba.fastjson2.JSON;
import com.zhg2yqq.wheels.common.response.RestResponse;
import com.zhg2yqq.wheels.common.util.ServletUtils;
import com.zhg2yqq.wheels.security.ISecurityEventHook;
import com.zhg2yqq.wheels.security.constants.SecurityResponseCode;

/**
 * @author zhg2yqq, 2022年11月28日
 * @version zhg2yqq v1.0
 */
public class SessionInformationExpiredHandler implements SessionInformationExpiredStrategy {
    private Logger log = LoggerFactory.getLogger(SessionInformationExpiredHandler.class);
    private ISecurityEventHook eventHook;

    public SessionInformationExpiredHandler() {
        super();
    }

    public SessionInformationExpiredHandler(ISecurityEventHook eventHook) {
        super();
        this.eventHook = eventHook;
    }

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent)
            throws IOException {
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();

        if (ServletUtils.isAjaxRequest(sessionInformationExpiredEvent.getRequest())) {
            // 允许跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            // 允许自定义请求头token(允许head跨域)
            response.setHeader("Access-Control-Allow-Headers",
                    "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(
                    JSON.toJSONString(RestResponse.fail(SecurityResponseCode.SECURITY_MAX_LOGIN)));
        }
    }
}
